<!DOCTYPE html>
<html>
  <head>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport">
  <meta name="description" content="along&#39;s blog">
  <meta name="keyword" content="hexo-theme, vuejs">
  
    <link rel="shortcut icon" href="/css/images/logo.png">
  
  <title>
    
      位运算 | ALONG
    
  </title>
  <link href="/cdn.along/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href="/cdn.along/nprogress/0.2.0/nprogress.min.css" rel="stylesheet">
  <link href="/cdn.along/highlight.js/9.12.0/styles/tomorrow.min.css" rel="stylesheet">
  
<link rel="stylesheet" href="/css/style.css">

  
  <script src="/cdn.along/jquery/3.2.1/jquery.min.js"></script>
  <script src="/cdn.along/geopattern/1.2.3/js/geopattern.min.js"></script>
  <script src="/cdn.along/nprogress/0.2.0/nprogress.min.js"></script>
  
    
<script src="/js/qrious.js"></script>

  
  
  
  
    <!-- MathJax support START -->
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="/cdn.along/mathjax/2.7.5/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
    <!-- MathJax support END -->
  


  
  
    
<script src="/js/local-search.js"></script>


<meta name="generator" content="Hexo 5.4.0"></head>
<div class="wechat-share">
  <img src="/css/images/logo.png" />
</div>
  <body>
    <header class="header fixed-header">
  <div class="header-container">
    <a class="home-link" href="/">
      <div class="logo"></div>
      <span>ALONG</span>
    </a>
    <ul class="right-list">
      
        <li class="list-item">
          
            <a href="/" class="item-link">Home</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/tags/" class="item-link">Tags</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/archives/" class="item-link">Archives</a>
          
        </li>
      
        <li class="list-item">
          
            <a href="/about/" class="item-link">About</a>
          
        </li>
      
      
        <li class="menu-item menu-item-search right-list">
    <a role="button" class="popup-trigger">
        <i class="fa fa-search fa-fw"></i>
    </a>
</li>
      
    </ul>
    <div class="menu">
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
      <span class="icon-bar"></span>
    </div>
    <div class="menu-mask">
      <ul class="menu-list">
        
          <li class="menu-item">
            
              <a href="/" class="menu-link">Home</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/tags/" class="menu-link">Tags</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/archives/" class="menu-link">Archives</a>
            
          </li>
        
          <li class="menu-item">
            
              <a href="/about/" class="menu-link">About</a>
            
          </li>
        
      </ul>
    </div>
    
      <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
            <span class="search-icon">
                <i class="fa fa-search"></i>
            </span>
            <div class="search-input-container">
                <input autocomplete="off" autocapitalize="off"
                    placeholder="Please enter your keyword(s) to search." spellcheck="false"
                    type="search" class="search-input">
            </div>
            <span class="popup-btn-close">
                <i class="fa fa-times-circle"></i>
            </span>
        </div>
        <div id="search-result">
            <div id="no-result">
                <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
            </div>
        </div>
    </div>
</div>
    
  </div>
</header>

    <div id="article-banner">
  <h2>位运算</h2>
  <p class="post-date">2021-01-06</p>
  <div class="arrow-down">
    <a href="javascript:;"></a>
  </div>
</div>
<main class="app-body flex-box">
  <!-- Article START -->
  <article class="post-article">
    <section class="markdown-content"><p>一、位运算<br>二进制：计算机中所有数据的存储和运算都是以二进制（补码）的形式进行的, 数字是四个字节，一个字节为8位，则一个数字是由32位二进制表示的<br>    a -&gt; 97, A -&gt; 65, ‘0’ -&gt; 48<br>举例：5 , -5<br>    原码：<br>    5: 0000 0000  0000 0000  0000 0000  0000 0101<br>    -5:1000 0000  0000 0000  0000 0000  0000 0101<br>    反码：（将原码）符号位不变，数值位取反（0变1，1变0）<br>    5: 0000 0000  0000 0000  0000 0000  0000 0101<br>    -5:1111 1111  1111 1111  1111 1111  1111 1010<br>    补码：负数等于反码+1,如果负数反码全是1, 则最后补码全是0, 正数与源码反码一样。<br>    5: 0000 0000  0000 0000  0000 0000  0000 0101<br>    -5:1111 1111  1111 1111  1111 1111  1111 1011<br>结论：正数的原码、反码、补码都是一样的<br>    0：0000 0000  0000 0000  0000 0000  0000 0000<br>    -0:1000 0000  0000 0000  0000 0000  0000 0000<br>位运算符：7个<br>    &amp;（按位与，and）：两个数字同为1，则为1，否则就是0<br>    |（按位或，or）：两个数字只要有一个是1，则结果为1<br>    ^（按位异或，xor）：两个数字不相同为1，相同为0<br>    ~（按位取反，not）：0变1，1变0<br>    &lt;&lt;（左移，shl）：a shl b，把二进制数a左移b位，在后面补0，相当于a乘以2的b次方，保留符号位<br>    &gt;&gt;（右移，shr）：把a右移b位（去掉末b位），相当于a除以2的b次方，高位补原符号位（0或1）， 保留符号位<br>    &gt;&gt;&gt;（无符号右移）：把a右移b位（去掉末b位），相当于a除以2的b次方，高位补0</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">5</span>, b = <span class="number">-5</span>, c = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// a b c 的 补码分别为</span></span><br><span class="line"><span class="comment">// 5: 0000 0000 0000 0000 0000 0000 0000 0101</span></span><br><span class="line"><span class="comment">// -5:1000 0000 0000 0000 0000 0000 0000 0101</span></span><br><span class="line"><span class="comment">// 2  0000 0000 0000 0000 0000 0000 0000 0010</span></span><br><span class="line">a &amp; c  <span class="comment">// 0</span></span><br><span class="line"></span><br><span class="line">a | c <span class="comment">// 7</span></span><br><span class="line"></span><br><span class="line">a ^ c <span class="comment">// 7 </span></span><br><span class="line">   </span><br><span class="line">~a    <span class="comment">// -6  // 5 的补码全取反=&gt; 1111 1111 1111 1111 1111 1111 1111 1010 =&gt; 减去1算出反码 =&gt; 1111 1111 1111 1111 1111 1111 1111 1001 =&gt; 反码推算出源码 =&gt;  1000 0000 0000 0000 0000 0000 0000 0110 =&gt; -6</span></span><br><span class="line"></span><br><span class="line">~b    <span class="comment">// 4   //  -5 的补码1111 1111  1111 1111  1111 1111  1111 1011全取反 =&gt; 0000 0000 0000 0000 0000 0000 0000 0100 =&gt; 推导出源码 =&gt; 4</span></span><br><span class="line"></span><br><span class="line">a &lt;&lt; <span class="number">2</span> <span class="comment">// 20	// 0000 0000 0000 0000 0000 0000 0001 0100 </span></span><br><span class="line"></span><br><span class="line">b &gt;&gt; <span class="number">2</span> <span class="comment">// -2</span></span><br><span class="line"></span><br><span class="line">b &lt;&lt; <span class="number">2</span> <span class="comment">// -20</span></span><br><span class="line"></span><br><span class="line">b &gt;&gt;&gt; <span class="number">2</span> <span class="comment">// 1073741822</span></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>应用场景</p>
<p>&amp; 按位与</p>
<ul>
<li>取模 a % b == a &amp; (b - 1) , 只能在b 为 2^n时使用</li>
<li>奇偶数判断,正负数都可以<ul>
<li>偶数 a &amp; 1 = 0;</li>
<li>奇数 a &amp; 1 = 1;</li>
</ul>
</li>
</ul>
<p>^ 异或<br>    一个数字异或另一个数字两次等于概数本身</p>
<ul>
<li>两数字交换<ul>
<li>a = 3, b = 4<ul>
<li>a = a ^ b</li>
<li>b = a ^ b</li>
<li>a = a ^ b</li>
<li>=&gt; a = 4, b = 3</li>
</ul>
</li>
</ul>
</li>
<li>给定一个数组，这个数组中所有的数字都出现两次，只有一个数字出现一次，找出出现一次的数字<ul>
<li>[2,3,4,3,2,5,5]<ul>
<li>遍历数组中的数字，一直执行异或操作</li>
<li>2 ^ 3 ^ 4 ^ 3 ^ 2 ^ 5 ^ 5 =&gt; 4 </li>
</ul>
</li>
</ul>
</li>
</ul>
</section>
    <!-- Tags START -->
    
    <!-- Tags END -->
    <!-- NAV START -->
    
  <div class="nav-container">
    <!-- reverse left and right to put prev and next in a more logic postition -->
    
      <a class="nav-left" href="/2020/11/19/%E5%BE%AE%E4%BF%A1%E5%BC%80%E5%8F%91%E8%80%85%E5%B7%A5%E5%85%B7/">
        <span class="nav-arrow">← </span>
        
          微信开发者工具
        
      </a>
    
    
      <a class="nav-right" href="/2021/01/14/redux/">
        
          redux
        
        <span class="nav-arrow"> →</span>
      </a>
    
  </div>

    <!-- NAV END -->
    <!-- 打赏 START -->
    
      <div class="money-like">
        <div class="reward-btn">
          赏
          <span class="money-code">
            <span class="alipay-code">
              <div class="code-image"></div>
              <b>使用支付宝打赏</b>
            </span>
            <span class="wechat-code">
              <div class="code-image"></div>
              <b>使用微信打赏</b>
            </span>
          </span>
        </div>
        <p class="notice">若你觉得我的文章对你有帮助，欢迎点击上方按钮对我打赏</p>
      </div>
    
    <!-- 打赏 END -->
    <!-- 二维码 START -->
    
      <div class="qrcode">
        <canvas id="share-qrcode"></canvas>
        <p class="notice">扫描二维码，分享此文章</p>
      </div>
    
    <!-- 二维码 END -->
    
      <!-- No Comment -->
    
  </article>
  <!-- Article END -->
  <!-- Catalog START -->
  
    <aside class="catalog-container">
  <div class="toc-main">
    <strong class="toc-title">Catalog</strong>
    
      <ol class="nav">none</ol>
    
  </div>
</aside>
  
  <!-- Catalog END -->
</main>

<script>
  (function () {
    var url = 'https://github.com/alongithub/2021/01/06/位运算/';
    var banner = ''
    if (banner !== '' && banner !== 'undefined' && banner !== 'null') {
      $('#article-banner').css({
        'background-image': 'url(' + banner + ')'
      })
    } else {
      $('#article-banner').geopattern(url)
    }
    $('.header').removeClass('fixed-header')

    // error image
    $(".markdown-content img").on('error', function() {
      $(this).attr('src', '/css/images/error_icon.png')
      $(this).css({
        'cursor': 'default'
      })
    })

    // zoom image
    $(".markdown-content img").on('click', function() {
      var src = $(this).attr('src')
      if (src !== '/css/images/error_icon.png') {
        var imageW = $(this).width()
        var imageH = $(this).height()

        var zoom = ($(window).width() * 0.95 / imageW).toFixed(2)
        zoom = zoom < 1 ? 1 : zoom
        zoom = zoom > 2 ? 2 : zoom
        var transY = (($(window).height() - imageH) / 2).toFixed(2)

        $('body').append('<div class="image-view-wrap"><div class="image-view-inner"><img src="'+ src +'" /></div></div>')
        $('.image-view-wrap').addClass('wrap-active')
        $('.image-view-wrap img').css({
          'width': `${imageW}`,
          'transform': `translate3d(0, ${transY}px, 0) scale3d(${zoom}, ${zoom}, 1)`
        })
        $('html').css('overflow', 'hidden')

        $('.image-view-wrap').on('click', function() {
          $(this).remove()
          $('html').attr('style', '')
        })
      }
    })
  })();
</script>


  <script>
    var qr = new QRious({
      element: document.getElementById('share-qrcode'),
      value: document.location.href
    });
  </script>






    <div class="scroll-top">
  <span class="arrow-icon"></span>
</div>
    <footer class="app-footer">
  <p class="copyright">
    Copyright&copy; 2019-2022 along
    <br>
    <a href="https://beian.miit.gov.cn/" target="_blank">京ICP备2020044791号-1</a>
    <!-- <br>
    Theme by <a href="https://github.com/alongithub">alongithub</a>
     -->
  </p>
</footer>

<script>
  function async(u, c) {
    var d = document, t = 'script',
      o = d.createElement(t),
      s = d.getElementsByTagName(t)[0];
    o.src = u;
    if (c) { o.addEventListener('load', function (e) { c(null, e); }, false); }
    s.parentNode.insertBefore(o, s);
  }
</script>
<script>
  async("/cdn.along/fastclick/1.0.6/fastclick.min.js", function(){
    FastClick.attach(document.body);
  })
</script>

<script>
  var hasLine = 'true';
  async("/cdn.along/highlight.js/9.12.0/highlight.min.js", function(){
    $('figure pre').each(function(i, block) {
      var figure = $(this).parents('figure');
      if (hasLine === 'false') {
        figure.find('.gutter').hide();
      }
      hljs.configure({useBR: true});
      var lang = figure.attr('class').split(' ')[1] || 'code';
      var codeHtml = $(this).html();
      var codeTag = document.createElement('code');
      codeTag.className = lang;
      codeTag.innerHTML = codeHtml;
      $(this).attr('class', '').empty().html(codeTag);
      figure.attr('data-lang', lang.toUpperCase());
      hljs.highlightBlock(block);
    });
  })
</script>
<!-- Baidu Tongji -->


<script src="/js/script.js"></script>


  </body>
</html>